package cn.xsw.utils;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.Data;
import lombok.experimental.Accessors;

@Data
@Accessors(chain = true)
public class IResult {

    private static final int SUCCESS = 200; //操作成功
    private static final int BAD_REQUEST = 400; //
    private static final int VALIDATE_FAILED = 404; //未找到资源或参数检验失败
    private static final int UNAUTHORIZED = 401; //暂未登录或token已经过期
    private static final int FORBIDDEN = 403; //没有相关权限
    private static final int INTERNAL_SERVER_ERROR = 500; //操作失败

    private int code;

    private String msg;

    private Object data;



    public IResult page(IPage ipage, boolean isPage) {
            return this.setData(new IPageBody().setResult(ipage.getRecords()).setTotal(ipage.getTotal()).setPageNo((ipage.getCurrent() / ipage.getSize()) + 1).setPageSize(ipage.getSize()));
    }

    public IResult success() {
        return this.setCode(SUCCESS).setMsg("success");
    }

    public IResult success(String msg) {
        return this.setCode(SUCCESS).setMsg(msg);
    }

    public IResult webError() {
        return this.setCode(BAD_REQUEST);
    }

    public IResult webError(String msg) {
        return this.setCode(BAD_REQUEST).setMsg(msg);
    }

    public IResult serverError() {
        return this.setCode(INTERNAL_SERVER_ERROR).setData("");
    }

    public IResult serverError(String msg) {
        return this.setCode(INTERNAL_SERVER_ERROR).setMsg(msg).setData("");
    }

    /**
     * 未登录返回结果
     */
    public static IResult unauthorized() {
        return new IResult().setCode(UNAUTHORIZED).setData("");
    }
    public static IResult unauthorized(String msg) {
        return new IResult().setCode(UNAUTHORIZED).setMsg(msg).setData("没有相关权限");
    }

    /**
     * 未授权返回结果
     */
    public static IResult forbidden() {
        return new IResult().setCode(FORBIDDEN).setData("");
    }
    public static IResult forbidden(String msg) {
        return new IResult().setCode(FORBIDDEN).setMsg(msg).setData("暂未登录或token已经过期");
    }

    @Override
    public String toString() {
        return JSONUtil.toJsonStr(this);
    }
}

@Data
@Accessors(chain = true)
class IPageBody {
    private Long pageNo;

    private Long pageSize;

    private Long total;

    private Object result;
}